<template>

  <div v-if="user">

    <van-cell title="昵称" is-link to="/user/edit" :value="user.username" @click="toEdit('username','昵称',user.username)" />
    <van-cell title="账户"  :value="user.userAccount" />

    <van-cell title="性别" is-link @click="()=>showPicker=true">
      <span v-if="user.gender===1">男</span>
      <span v-if="user.gender===0">女</span>
    </van-cell>

    <van-cell title="个人简介" is-link to="/user/edit" :value="user.profile"  @click="toEdit('profile','个人简介',user.profile)"/>
    <van-cell title="电话" is-link to="/user/edit" :value="user.phone"  @click="toEdit('phone','电话',user.phone)"/>
    <van-cell title="邮箱" is-link to="/user/edit" :value="user.email"  @click="toEdit('email','邮箱',user.email)"/>
    <van-cell title="注册时间"  :value="user.createTime"  />
    <van-cell value="点击查看" icon="label-o" is-link
              @click="tagUpdate('tags','我的标签',user.tags)">
      <template #title>
        <span class="custom-title">我的标签</span>
      </template>
    </van-cell>
    <van-popup  v-model:show="showPicker"  round position="bottom" >
      <van-picker
          :columns="gender"
          @confirm="onConfirm"
          @cancel="showPicker = false"
      />
    </van-popup>
  </div>


  <copyright/>
</template>

<script lang="ts" setup >
import {useRouter} from "vue-router";
import {onMounted, ref} from "vue";
import {showFailToast, showSuccessToast} from "vant";
import {getCurrentUser} from "../services/user.ts";
import myAxios from "../plugins/myAxios.ts";

const router = useRouter();
const user = ref();




onMounted(async ()=>{
  //获取用户信息
  //const res = await myAxios.get('/user/current');
  // 异步方法必须添加await才可以拿到数据，否则拿到的是promise对象
  const  res = await  getCurrentUser();

  if (res){
    user.value = res;
    //console.log("----user:----", user.value);
    //showSuccessToast('获取用户信息成功');
  }else {
    showFailToast('获取用户信息失败');
  }
})



const showPicker = ref(false);
const gender = [
  {text: '男', value: '1'},
  {text: '女', value: '0'},
];
const onConfirm = async  ({selectedValues}) => {

  const currentUser = await getCurrentUser();
  if(!currentUser){
    showFailToast("用户未登录");
    return;
  }
  currentUser.gender = selectedValues[0];
  //console.log('-----------gender:--------',selectedValues[0]);
  const res = await myAxios.post("/user/update", {
    'id' : currentUser.id,
    'gender' : currentUser.gender
  })

  if(res.code===0&&res.data>0){
    showSuccessToast('修改成功');
    //todo 自动刷新
  }else{
    showFailToast('修改错误');
  }
     showPicker.value = false;
};




const toEdit = (editKey,editName,currentValue) =>{
  router.push({
    path:'/user/edit',
    query: {
      editKey,
      editName,
      currentValue,
    }
  })
}

const tagUpdate = (editKey: string, editName: string, currentValue) => {
  router.push({
    path: "/updateTags",
    query: {
      editKey,
      editName,
      currentValue,
      // id: id,
      // tags: JSON.parse(tags),
    }
  })
}


</script>

<style scoped>

</style>
